package com.sunny.design.delegate.mvc;

import com.sunny.design.delegate.mvc.controller.MemberController;
import com.sunny.design.delegate.mvc.controller.OrderController;
import com.sunny.design.delegate.mvc.controller.ProductController;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 仿照Spring实现的极简方式
 * 在 Spring 源码中，只要以 Delegate 结尾的都是实现了委派模式
 *
 * @author Sunny
 * @date 2020/1/4 17:40
 */
public class DispatcherServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doDispatch(req, resp);
    }

    /**
     * 根据不同的uri 委派到不同的controller执行
     *
     * @param req
     * @param resp
     * @throws IOException
     */
    public void doDispatch(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String uri = req.getRequestURI();
        String mid = req.getParameter("mid");
        String oid = req.getParameter("oid");
        String pid = req.getParameter("pid");
        if ("getMemberById".equals(uri)) {
            new MemberController().getMemberById(mid);
        } else if ("getOrderById".equals(uri)) {
            new OrderController().getOrderById(oid);
        } else if ("getProductById".equals(uri)) {
            new ProductController().getProductById(pid);
        } else {
            resp.getWriter().write("404 Not Found!!");
        }
    }
}
